package com.qf.aop.async;

import cn.hutool.core.date.DateUtil;
import com.qf.aop.config.Ip2regionUtil;
import com.qf.api.entity.SysLoginLogEntity;
import com.qf.api.entity.SysOperationLogEntity;
import com.qf.api.service.SysLoginLogService;
import com.qf.api.service.SysOperationLogService;
import com.qf.core.enums.common.LoginStatusEnum;
import com.qf.core.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: sin
 * @Date: 2025/5/9 15:06
 * @Description: 异步工厂（产生任务用）
 **/
@Slf4j
@Component
public class AsyncTaskFactory {

    @Autowired
    private SysLoginLogService loginLogService;

    @Autowired
    private SysOperationLogService operationLogService;

    private AsyncTaskFactory() {
    }

    /**
     * 记录登录信息
     *
     * @param username        用户名
     * @param loginStatusEnum 状态
     * @param message         消息
     * @return 任务task
     */
    public Runnable loginInfoTask(final String username, final LoginStatusEnum loginStatusEnum, final String message) {
        HttpServletRequest request = ServletUtils.getRequest();
        // 获取客户端浏览器
        final String browser = Ip2regionUtil.getBrowser(request);
        final String ip = Ip2regionUtil.getIpAddr(request);
        final String ipAddr = Ip2regionUtil.getAddr(ip);
        final String operationSystem = Ip2regionUtil.getOs(request);
        return () -> {
            // 封装对象
            SysLoginLogEntity loginInfo = new SysLoginLogEntity();
            loginInfo.setUsername(username);
            loginInfo.setIpAddress(ip);
            loginInfo.setLoginLocation(ipAddr);
            loginInfo.setBrowser(browser);
            loginInfo.setOperationSystem(operationSystem);
            loginInfo.setMsg(message);
            loginInfo.setLoginTime(DateUtil.date());
            loginInfo.setStatus(loginStatusEnum.getValue());
            // 插入数据
            loginLogService.save(loginInfo);
        };
    }

    /**
     * 操作日志记录
     *
     * @param operationLog 操作日志信息
     * @return 任务task
     */
    public Runnable recordOperationLog(final SysOperationLogEntity operationLog) {
        return () -> {
            operationLogService.save(operationLog);
        };
    }
}
